<?
/**
 * Copyright 2007 Melange.
 *
 * This file is part of PHP-HTTP.
 *
 * PHP-HTTP is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * PHP-HTTP is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with PHP-HTTP; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category    Melange
 * @package     php-http
 * @copyright   Copyright (c) 2007 Jeroen Simons. All rights reserved
 * @author      Jeroen Simons <jeroen@melange.nl>
 * @link        http://www.melange.nl/
 *
 */


/**
 * Convenience base implementation of the <b>HttpResponse</b> interface, which
 * can be used for the <code>Response</code> implementation required by most
 * <code>Connectors</code> that deal with HTTP.  Only the connector-specific
 * methods need to be implemented.
 *
 */
class Response {


    // -------------------------------------------------------------- Constants


    /**
     * The name of the cookie used to pass the session identifier back
     * and forth with the client.
     */
    const SESSION_COOKIE_NAME = "PHPSESSID";


    // ----------------------------------------------------------- Constructors


    public function __construct() {
        $this->message = $this->getStatusMessage(self::SC_OK);
//        $this->locale = Locale::getDefault();
    }


    // ----------------------------------------------------- Instance Variables


    protected $characterEncoding = "UTF-8";


    /**
     * The application commit flag.
     */
    protected $appCommitted = false;


    /**
     * The set of Cookies associated with this Response.
     */
    protected $cookies = array();


    /**
     * Has this response been committed yet?
     */
    protected $committed = false;


    /**
     * The date format we will use for creating date headers.
     * EEE, dd MMM yyyy HH:mm:ss zzz
     */
    protected $format = "D, d M Y H:i:s T";


    /**
     * The HTTP headers explicitly added via addHeader(), but not including
     * those to be added with setContentLength(), setContentType(), and so on.
     * This collection is keyed by the header name, and the elements are
     * ArrayLists containing the associated values that have been set.
     */
    protected $headers = array();


    /**
     * Associated output buffer.
     */
    protected $outputBuffer;


    /**
     * The error message set by <code>sendError()</code>.
     */
    protected $message = null;


    /**
     * The HTTP status code associated with this Response.
     */
    protected $status = self::SC_OK;


    /**
     * The time zone with which to construct date headers.
     */
    protected $zone = "GMT";


    /**
     * Buffer replacement for a PrintWriter
     */
    protected $body = "";


    /**
     * Recyclable buffer to hold the redirect URL.
     */
    protected $redirectURLCC = "";


    /**
     * Has this response output been suspended?
     */
    protected $suspended = false;


    /**
     * Error flag. True if the response is an error report.
     */
    protected $error = false;


    /**
     * Are we currently processing inside a RequestDispatcher.include()?
     */
    protected $included = false;


    /**
     * The actual number of bytes written to this Response.
     */
    protected $contentCount = 0;


    /**
     * The content length associated with this Response.
     */
    protected $contentLength = -1;


    /**
     * The content type associated with this Response.
     */
    protected $contentType = null;


    /**
     * The Context within which this Response is being produced.
     */
    protected $context = null;


    /**
     * The character encoding associated with this Response.
     */
    protected $encoding = null;


    /**
     * The Locale associated with this Response.
     */
    protected $locale = null;


    /**
     * The Request with which this Response is associated.
     */
    protected $request = null;


    // --------------------------------------------------------- Public Methods


    /**
     * Set the application commit flag.
     *
     * @param appCommitted The new application committed flag value
     */
    public function setAppCommitted($appCommitted) {
        $this->appCommitted = $appCommitted;
    }


    /**
     * Application commit flag accessor.
     */
    public function isAppCommitted() {
        return ($this->appCommitted || $this->isCommitted() || $this->isSuspended()
                || (($this->getContentLength() > 0)
                    && ($this->getContentCount() >= $this->getContentLength())));
    }


    /**
     * Return the number of bytes actually written to the output stream.
     */
    public function getContentCount() {

        return ($this->contentCount);

    }


    /**
     * Return the content length that was set or calculated for this Response.
     */
    public function getContentLength() {

        return ($this->contentLength);

    }


    /**
     * Return the content type that was set or calculated for this response,
     * or <code>null</code> if no content type was set.
     */
    public function getContentType() {

        return ($this->contentType);

    }


    /**
     * Return the Context with which this Response is associated.
     */
    public function getContext() {

        return ($this->context);

    }


    /**
     * Set the Context with which this Response is associated.  This should
     * be called as soon as the appropriate Context is identified.
     *
     * @param context The associated Context
     */
    public function setContext($context) {

        $this->context = $context;

    }


    /**
     * Return the "processing inside an include" flag.
     */
    public function getIncluded() {

        return ($this->included);

    }


    /**
     * Set the "processing inside an include" flag.
     *
     * @param included <code>true</code> if we are currently inside a
     *  RequestDispatcher.include(), else <code>false</code>
     */
    public function setIncluded($included) {

        $this->included = $included;

    }


    /**
     * Return the Request with which this Response is associated.
     */
    public function getRequest() {

        return ($this->request);

    }


    /**
     * Set the Request with which this Response is associated.
     *
     * @param request The new associated request
     */
    public function setRequest(Request $request) {

        $this->request = $request;

    }


    /**
     * Return the OutputBuffer with which this Response is associated.
     */
    public function getOutputBuffer() {
        return $this->outputBuffer;
    }


    /**
     * Set the OutputBuffer with which this Response is associated.
     *
     * @param outputBuffer The new associated outputBuffer
     */
    public function setOutputBuffer(OutputBuffer &$outputBuffer) {
        $this->outputBuffer = $outputBuffer;
    }


    /**
     * Return the writer associated with this Response.
     *
     * @throws IllegalStateException if <code>getOutputStream</code> has
     *                               already been called for this response
     * @throws IOException           if an input/output error occurs
     */
    public function getWriter() {

//        $this->setCharacterEncoding($this->getCharacterEncoding());

        if ($this->writer === null) {
            require_once("http/Writer.php");
            $this->writer = new Writer($this->outputBuffer);
        }

        return $this->writer;

    }


    /**
     * Replacement of PrintWriter
     */
//    public function _print($s) {
//        $this->body .= $s;
//        $this->contentCount++;
//    }


    /**
     * Perform whatever actions are required to flush and close the output
     * stream or writer, in a single operation.
     *
     * @exception IOException if an input/output error occurs
     */
    public function finishResponse() {

        // Commit current response
        if ($this->isCommitted())
            return;

        // If an HTTP error >= 400 has been created with no content,
        // attempt to create a simple error message
        if (($this->status >= self::SC_BAD_REQUEST) &&
            ($this->contentType == null) &&
            ($this->outputBuffer->getCharsWritten() == 0)) {

            try {
                $this->setContentType("text/html");
                $this->outputBuffer->write("<html>\n");
                $this->outputBuffer->write("<head>\n");
                $this->outputBuffer->write("<title>PHP Error Report</title>\n");
                $this->outputBuffer->write("</head>\n");
                $this->outputBuffer->write("<body>\n");
                $this->outputBuffer->write("<h4>HTTP Status ");
                $this->outputBuffer->write($this->status);
                $this->outputBuffer->write(" - ");
                if ($this->message !== null)
                    $this->outputBuffer->write($this->message);
                else
                    $this->outputBuffer->write($this->getStatusMessage($this->status));
                $this->outputBuffer->write("</h4>\n");
                $this->outputBuffer->write("</body>\n");
                $this->outputBuffer->write("</html>");
            } catch (Exception $e) {
                ;       // Just eat it
            }
        }

        // Flush the headers and finish this response
        $this->sendHeaders();

        $this->outputBuffer->commit();

        $this->committed = true;

        exit();

    }


    /**
     * Return an array of all cookies set for this response, or
     * a zero-length array if no cookies have been set.
     */
    public function getCookies() {

        return $this->cookies;

    }


    /**
     * Return the value for the specified header, or <code>null</code> if this
     * header has not been set.  If more than one value was added for this
     * name, only the first is returned; use getHeaderValues() to retrieve all
     * of them.
     *
     * @param name Header name to look up
     */
    public function getHeader($name) {

        $values = null;
        $values = array_key_exists($name, $this->headers) ?
            $this->headers[$name] : null;

        if ($values !== null)
            return is_array($values) ? $values[0] : $values;
        else
            return (null);

    }


    /**
     * Return an array of all the header names set for this response, or
     * a zero-length array if no headers have been set.
     */
    public function getHeaderNames() {

        return array_keys($this->headers);

    }


    /**
     * Return an array of all the header values associated with the
     * specified header name, or an zero-length array if there are no such
     * header values.
     *
     * @param name Header name to look up
     */
    public function getHeaderValues($name) {

        return array_key_exists($name, $this->headers) ?
            array_values($this->headers[$name]) : array();

    }


    /**
     * Return the error message that was set with <code>sendError()</code>
     * for this Response.
     */
    public function getMessage() {

        return ($this->message);

    }


    /**
     * Return the HTTP status code associated with this Response.
     */
    public function getStatus() {

        return ($this->status);

    }


    /**
     * Release all object references, and initialize instance variables, in
     * preparation for reuse of this object.
     */
    public function recycle() {

        $this->cookies = array();
        $this->headers = array();
        $this->message = $this->getStatusMessage(self::SC_OK);
        $this->status  = HttpServletResponse::SC_OK;

    }


    /**
     * Reset this response, and specify the values for the HTTP status code
     * and corresponding message.
     *
     * @exception IllegalStateException if this response has already been
     *  committed
     */
    public function reset($status = null, $message = null) {

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->cookies = array();
        $this->headers = array();
        $this->message = $message;
        $this->status  = $status !== null ? $status : self::SC_OK;

        $this->setStatus($status, $message);

    }


    /**
     * Reset the data buffer but not any status or header information.
     *
     * @exception IllegalStateException if the response has already
     *  been committed
     */
    public function resetBuffer() {

        if ($this->committed)
            throw new Exception("Cannot reset buffer after response has been committed");

        $this->outputBuffer->reset();

    }


    /**
     * Has the output of this response already been committed?
     */
    public function isCommitted() {

        return ($this->committed);

    }


    // ------------------------------------------------------ Protected Methods


    /**
     * Returns a default status message for the specified HTTP status code.
     *
     * @param status The status code for which a message is desired
     */
    protected function getStatusMessage($status) {

        switch ($status) {
        case self::SC_OK:
            return ("OK");
        case self::SC_ACCEPTED:
            return ("Accepted");
        case self::SC_BAD_GATEWAY:
            return ("Bad Gateway");
        case self::SC_BAD_REQUEST:
            return ("Bad Request");
        case self::SC_CONFLICT:
            return ("Conflict");
        case self::SC_CONTINUE:
            return ("Continue");
        case self::SC_CREATED:
            return ("Created");
        case self::SC_EXPECTATION_FAILED:
            return ("Expectation Failed");
        case self::SC_FORBIDDEN:
            return ("Forbidden");
        case self::SC_GATEWAY_TIMEOUT:
            return ("Gateway Timeout");
        case self::SC_GONE:
            return ("Gone");
        case self::SC_HTTP_VERSION_NOT_SUPPORTED:
            return ("HTTP Version Not Supported");
        case self::SC_INTERNAL_SERVER_ERROR:
            return ("Internal Server Error");
        case self::SC_LENGTH_REQUIRED:
            return ("Length Required");
        case self::SC_METHOD_NOT_ALLOWED:
            return ("Method Not Allowed");
        case self::SC_MOVED_PERMANENTLY:
            return ("Moved Permanently");
        case self::SC_MOVED_TEMPORARILY:
            return ("Moved Temporarily");
        case self::SC_MULTIPLE_CHOICES:
            return ("Multiple Choices");
        case self::SC_NO_CONTENT:
            return ("No Content");
        case self::SC_NON_AUTHORITATIVE_INFORMATION:
            return ("Non-Authoritative Information");
        case self::SC_NOT_ACCEPTABLE:
            return ("Not Acceptable");
        case self::SC_NOT_FOUND:
            return ("Not Found");
        case self::SC_NOT_IMPLEMENTED:
            return ("Not Implemented");
        case self::SC_NOT_MODIFIED:
            return ("Not Modified");
        case self::SC_PARTIAL_CONTENT:
            return ("Partial Content");
        case self::SC_PAYMENT_REQUIRED:
            return ("Payment Required");
        case self::SC_PRECONDITION_FAILED:
            return ("Precondition Failed");
        case self::SC_PROXY_AUTHENTICATION_REQUIRED:
            return ("Proxy Authentication Required");
        case self::SC_REQUEST_ENTITY_TOO_LARGE:
            return ("Request Entity Too Large");
        case self::SC_REQUEST_TIMEOUT:
            return ("Request Timeout");
        case self::SC_REQUEST_URI_TOO_LONG:
            return ("Request URI Too Long");
        case self::SC_REQUESTED_RANGE_NOT_SATISFIABLE:
            return ("Requested Range Not Satisfiable");
        case self::SC_RESET_CONTENT:
            return ("Reset Content");
        case self::SC_SEE_OTHER:
            return ("See Other");
        case self::SC_SERVICE_UNAVAILABLE:
            return ("Service Unavailable");
        case self::SC_SWITCHING_PROTOCOLS:
            return ("Switching Protocols");
        case self::SC_UNAUTHORIZED:
            return ("Unauthorized");
        case self::SC_UNSUPPORTED_MEDIA_TYPE:
            return ("Unsupported Media Type");
        case self::SC_USE_PROXY:
            return ("Use Proxy");
        case 207:       // WebDAV
            return ("Multi-Status");
        case 422:       // WebDAV
            return ("Unprocessable Entity");
        case 423:       // WebDAV
            return ("Locked");
        case 507:       // WebDAV
            return ("Insufficient Storage");
        default:
            return ("HTTP Response Status " . status);
        }

    }


    /**
     * Return <code>true</code> if the specified URL should be encoded with
     * a session identifier.  This will be true if all of the following
     * conditions are met:
     * <ul>
     * <li>The request we are responding to asked for a valid session
     * <li>The requested session ID was not received via a cookie
     * <li>The specified URL points back to somewhere within the web
     *     application that is responding to this request
     * </ul>
     *
     * @param location Absolute URL to be validated
     **/
    private function isEncodeable($location) {

        if ($location === null)
            return (false);

        // Is this an intra-document reference?
        if (strpos($location, "#") === 0)
            return (false);

        // Are we in a valid session that is not using cookies?
        $hreq = $this->request;
        $session = $hreq->getSession(false);
        if ($session === null)
            return (false);

        if ($hreq->isRequestedSessionIdFromCookie())
            return (false);

        // Is this a valid absolute URL?
        $url = null;
        try {
            $url = parse_url($location);
        } catch (Exception $e) {
            return (false);
        }

        // Does this URL match down to (and including) the context path?
        if (!strtolower($hreq->getScheme()) == strtolower($url["scheme"]))
            return (false);
        if (!strtolower($hreq->getServerName()) == strtolower($url["host"]))
            return (false);

        $serverPort = $hreq->getServerPort();
        if ($serverPort == -1) {
            if ("https" == $hreq->getScheme())
                $serverPort = 443;
            else
                $serverPort = 80;
        }
        $urlPort = array_key_exists("port", $url) ?
            $url["port"] : null;

        if ($urlPort === null) {
            if ("https" == $url["scheme"])
                $urlPort = 443;
            else
                $urlPort = 80;
        }
        if ($serverPort != $urlPort)
            return (false);

        $contextPath = $hreq->getContextPath();
        if (($contextPath !== null) && (strlen($contextPath) > 0)) {
            $file = $url["path"];
            if (($file === null) || (strpos($file, $contextPath) !== 0))
                return (false);
            if(array_key_exists("query", $url) &&
                    strpos($url["query"], self::SESSION_COOKIE_NAME."=" . $session->getId()) !== false) {
                return (false);
            }
        }

        // This URL belongs to our web application, so it is encodeable
        return (true);

    }


    /**
     * Return the HTTP protocol version implemented by this response
     * object. (This method must be overridden by subclasses of this
     * as to correctly return the highest HTTP version number supported
     * as specified in Section 3.1 of RFC-2616).
     *
     * @return A string in the form of &quot;HTTP/1.0&quot; ...
     */
    protected function getProtocol() {
        return($this->request->getProtocol());
    }


    /**
     * Send the HTTP response headers, if this has not already occurred.
     */
    protected function sendHeaders() {

        if ($this->isCommitted())
            return;

        // Check if the request was an HTTP/0.9 request
        if ("HTTP/0.9" == $this->request->getProtocol()) {
            $this->committed = true;
            return;
        }

        // Send the "Status:" header

        $status = $this->getProtocol();
        $status .= " ";
        $status .= $this->status;
        if ($this->message !== null) {
            $status .= " ";
            $status .= $this->message;
        }

        header($status);

         /* Following line added to fix a bug in PHP-CGI where the status code is not properly set */
        header("Status: " . $this->status);

        // Send the content-length and content-type headers (if any)
        if ($this->getContentType() !== null) {

            header("Content-Type: " . $this->getContentType());
        }
        if ($this->getContentLength() >= 0) {

            header("Content-Length: " . $this->getContentLength());
        }

        // Send all specified headers (if any)
        $names = $this->getHeaderNames();
        foreach($names as $name) {
            $values = $this->headers[$name];
            $items = is_array($values) ? $values : array($values);
            foreach ($items as $value) {
                header($name.": " . $value);
            }
        }

        // Send all specified cookies (if any)
        foreach($this->cookies as $cookie) {

            setcookie(
                $cookie->getName(),
                $cookie->getValue(),
                $cookie->getExpire(),
                $cookie->getPath(),
                $cookie->getDomain(),
                $cookie->getSecure(),
                $cookie->getHttponly()
            );
        }

        // The response is now committed
        $this->committed = true;

    }


    /**
     * Convert (if necessary) and return the absolute URL that represents the
     * resource referenced by this possibly relative URL.  If this URL is
     * already absolute, return it unchanged.
     *
     * @param location URL to be (possibly) converted and then returned
     *
     * @exception IllegalArgumentException if a MalformedURLException is
     *  thrown when converting the relative URL to an absolute one
     */
    private function toAbsolute($location) {

        if ($location === null)
            return (location);

        $leadingSlash = (strpos($location, "/") === 0);

        if ($leadingSlash || !$this->hasScheme($location)) {

            $this->redirectURLCC = "";

            $scheme = $this->request->getScheme();
            $name   = $this->request->getServerName();
            $port   = $this->request->getServerPort();

            try {
                $this->redirectURLCC .= $scheme;
                $this->redirectURLCC .= "://";
                $this->redirectURLCC .= $name;

                if (($scheme == "http" && $port != 80)
                    || ($scheme == "https" && $port != 443)) {
                    $this->redirectURLCC .= ':';
                    $this->redirectURLCC .= $port;
                }
                if (!$leadingSlash) {
                    $relativePath = $this->request->getDecodedRequestURI();
                    $pos = strrpos($relativePath, '/');
                    $relativePath = substr($relativePath, 0, $pos);

                    $encodedURI = null;
                    $frelativePath = $relativePath;
                    $encodedURI = $relativePath;

                    $this->redirectURLCC .= $encodedURI;
                    $this->redirectURLCC .= '/';
                }

                $this->redirectURLCC .= $location;

            } catch (Exception $e) {
                throw new Exception($location);
            }

            return $this->redirectURLCC;

        } else {

            return ($location);

        }

    }


    /**
     * Return the specified URL with the specified session identifier
     * suitably encoded.
     *
     * @param url URL to be encoded with the session id
     * @param sessionId Session id to be included in the encoded URL
     */
    private function toEncoded($url, $sessionId) {

        if (($url === null) || ($sessionId === null))
            return ($url);

        $path = $url;
        $query = "";
        $anchor = "";
        $question = strpos($url, "?");
        if ($question !== false) {
            $path = substr($url, 0, $question);
            $query = substr($url, $question);
        } else {
            $query = "?";
        }
        $pound = strpos($path, '#');
        if ($pound !== false) {
            $anchor = substr($path, $pound);
            $path = substr($path, 0, $pound);
        }
        $sb = $path;
        $sb .= $anchor;
        $sb .= $query;
        if(strlen($query) > 1)
            $sb .= "&";
        $sb .= self::SESSION_COOKIE_NAME."=";
        $sb .= $sessionId;

        return ($sb);

    }


    /**
     * Determine if a URI string has a <code>scheme</code> component.
     */
    private function hasScheme($uri) {

        $len = strlen($uri);
        for($i=0; $i < $len ; $i++) {
            $c = $uri[$i];
            if($c == ':') {
                return $i > 0;
            } else if(!self::isSchemeChar($c)) {
                return false;
            }
        }
        return false;
    }


    /**
     * Determine if the character is allowed in the scheme of a URI.
     * See RFC 2396, Section 3.1
     * Todo: removed ctype_alnum($c) here since not all servers support it.
     */
    public static function isSchemeChar($c) {
        return (preg_match("/[0-9]+/", $c) ||
            $c == '+' || $c == '-' || $c == '.');
    }



    // ------------------------------------------------ ServletResponse Methods


    /**
     * Flush the buffer and commit this response.  If this is the first output,
     * send the HTTP headers prior to the user data.
     *
     * @exception IOException if an input/output error occurs
     */
    public function flushBuffer() {

        $this->doFlushBuffer();

    }

    private function doFlushBuffer() {

        if (!$this->isCommitted())
            $this->sendHeaders();

        $this->committed = true;
        echo($this->body);

    }



    /**
     * Set the content length (in bytes) for this Response.
     *
     * @param length The new content length
     */
    public function setContentLength($length) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->setContentLength($length);

    }



    /**
     * Set the content type for this Response.
     *
     * @param type The new content type
     */
    public function setContentType($type) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->contentType = $type;

    }


    /**
     * Set the Locale that is appropriate for this response, including
     * setting the appropriate character encoding.
     *
     * @param locale The new locale
     */
    public function setLocale(Locale $locale) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->locale = $locale;
        $language = $locale->getLanguage();
        if (($language !== null) && (strlen($language) > 0)) {
            $country = $locale->getCountry();
            $value = $language;
            if (($country !== null) && (strlen($country) > 0)) {
                $value .= '-';
                $value .= $country;
            }
            $this->setHeader("Content-Language", $value);
        }

    }


    // -------------------------------------------- HttpServletResponse Methods


    /**
     * Add the specified Cookie to those that will be included with
     * this Response.
     *
     * @param cookie Cookie to be added
     */
    public function addCookie($cookie) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->cookies[] = $cookie;

    }


    /**
     * Add the specified date header to the specified value.
     *
     * @param name Name of the header to set
     * @param value Date value (long) to be set
     */
    public function addDateHeader($name, $value) {

        $this->addHeader($name, gmdate($this->format, $value));

    }


    /**
     * Add the specified header to the specified value.
     *
     * @param name Name of the header to set
     * @param value Value to be set
     */
    public function addHeader($name, $value) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $values = array_key_exists($name, $this->headers) ? $this->headers[$name] : null;
        if ($values === null) {
            $this->headers[$name] = array();
        }
        $this->headers[$name][] = $value;

    }


    /**
     * Add the specified integer header to the specified value.
     *
     * @param name Name of the header to set
     * @param value Integer value to be set
     */
    public function addIntHeader($name, $value) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->addHeader($name, "" . $value);

    }


    /**
     * Has the specified header been set already in this response?
     *
     * @param name Name of the header to check
     */
    public function containsHeader($name) {

        return array_key_exists($name, $this->headers);

    }


    /**
     * Encode the session identifier associated with this response
     * into the specified redirect URL, if necessary.
     *
     * @param url URL to be encoded
     */
    public function encodeRedirectURL($url) {

        if ($this->isEncodeable($this->toAbsolute($url))) {
            $hreq = $this->request;
            return ($this->toEncoded($url, $hreq->getSession()->getId()));
        } else
            return ($url);

    }


    /**
     * Encode the session identifier associated with this response
     * into the specified URL, if necessary.
     *
     * @param url URL to be encoded
     */
    public function encodeURL($url) {

        $absolute = $this->toAbsolute($url);
        if ($this->isEncodeable($absolute)) {
            // W3c spec clearly said
            if ($url == "") {
                $url = $absolute;
            }
            return ($this->toEncoded($url, $this->request->getSession()->getId()));
        } else
            return ($url);

    }


    /**
     * Send an acknowledgment of a request.
     *
     * @exception IOException if an input/output error occurs
     */
    public function sendAcknowledgement() {
    }


    /**
     * Send an error response with the specified status and message.
     *
     * @param status HTTP status code to send
     * @param message Corresponding message to send
     *
     * @exception IllegalStateException if this response has
     *  already been committed
     * @exception IOException if an input/output error occurs
     */
    public function sendError($status, $message = null)  {

        if ($this->isCommitted())
            throw new Exception("httpResponseBase.sendError.ise");

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->setError();

        // Record the status code and message.
        $this->status = $status;
        $this->message = $message !== null ? $message : $this->getStatusMessage($status);

        // Clear any data content that has been buffered
        $this->resetBuffer();

        // Cause the response to be finished (from the application perspective)
        $this->setSuspended(true);

    }


    /**
     * Send a temporary redirect to the specified redirect location URL.
     *
     * @param location Location URL to redirect to
     *
     * @exception IllegalStateException if this response has
     *  already been committed
     * @exception IOException if an input/output error occurs
     */
    public function sendRedirect($location) {

        if ($this->isCommitted())
            throw new Exception("Cannot call sendRedirect() after the response has been committed");

        if ($this->included)
            return;     // Ignore any call from an included servlet

        // Clear any data content that has been buffered
        $this->resetBuffer();

        // Generate a temporary redirect to the specified location
        try {
            $absolute = $this->toAbsolute($location);
            $this->setStatus(self::SC_MOVED_TEMPORARILY);
            $this->setHeader("Location", $absolute);
        } catch (Exception $e) {
            $this->setStatus(self::SC_NOT_FOUND);
        }

        // Cause the response to be finished (from the application perspective)
        $this->setSuspended(true);

    }


    /**
     * Set the specified date header to the specified value.
     *
     * @param name Name of the header to set
     * @param value Date value to be set
     */
    public function setDateHeader($name, $value) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->setHeader($name, gmdate("D, d M Y H:i:s T", $value));

    }


    /**
     * Set the specified header to the specified value.
     *
     * @param name Name of the header to set
     * @param value Value to be set
     */
    public function setHeader($name, $value) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $values = array();
        $values[] = $value;
        $this->headers[$name] = $values;

        $match = strtolower($name);
        if ($match == "content-length") {

            if(!is_numeric($value))
                throw new Exception("NumberFormatException");

            $contentLength = intval($value);

            if ($contentLength >= 0)
                $this->setContentLength($contentLength);

        } else if ($match == "content-type") {

            $this->setContentType($value);
        }

    }


    /**
     * Set the specified integer header to the specified value.
     *
     * @param name Name of the header to set
     * @param value Integer value to be set
     */
    public function setIntHeader($name, $value) {

        if ($this->isCommitted())
            return;

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->setHeader($name, "" . $value);

    }


    /**
     * Set the HTTP status and message to be returned with this response.
     *
     * @param status The new HTTP status
     * @param message The associated text message
     *
     * @deprecated As of Version 2.1 of the Java Servlet API, this method
     *  has been deprecated due to the ambiguous meaning of the message
     *  parameter.
     */
    public function setStatus($status, $message = null) {

        if ($this->included)
            return;     // Ignore any call from an included servlet

        $this->status = $status;
        $this->message = $message !== null ? $message : $this->getStatusMessage($status);

    }


    /**
     * Set the suspended flag.
     */
    public function setSuspended($suspended) {

        $this->suspended = $suspended;
//        if (stream != null)
//            ((ResponseStream) stream).setSuspended(suspended);

    }


    /**
     * Suspended flag accessor.
     */
    public function isSuspended() {

        return ($this->suspended);

    }


    /**
     * Set the error flag.
     */
    public function setError() {

        $this->error = true;

    }


    /**
     * Error flag accessor.
     */
    public function isError() {

        return ($this->error);

    }


    /*
     * Server status codes; see RFC 2068.
     */

    /**
     * Status code (100) indicating the client can continue.
     */

    const SC_CONTINUE = 100;


    /**
     * Status code (101) indicating the server is switching protocols
     * according to Upgrade header.
     */

    const SC_SWITCHING_PROTOCOLS = 101;

    /**
     * Status code (200) indicating the request succeeded normally.
     */

    const SC_OK = 200;

    /**
     * Status code (201) indicating the request succeeded and created
     * a new resource on the server.
     */

    const SC_CREATED = 201;

    /**
     * Status code (202) indicating that a request was accepted for
     * processing, but was not completed.
     */

    const SC_ACCEPTED = 202;

    /**
     * Status code (203) indicating that the meta information presented
     * by the client did not originate from the server.
     */

    const SC_NON_AUTHORITATIVE_INFORMATION = 203;

    /**
     * Status code (204) indicating that the request succeeded but that
     * there was no new information to return.
     */

    const SC_NO_CONTENT = 204;

    /**
     * Status code (205) indicating that the agent <em>SHOULD</em> reset
     * the document view which caused the request to be sent.
     */

    const SC_RESET_CONTENT = 205;

    /**
     * Status code (206) indicating that the server has fulfilled
     * the partial GET request for the resource.
     */

    const SC_PARTIAL_CONTENT = 206;

    /**
     * Status code (300) indicating that the requested resource
     * corresponds to any one of a set of representations, each with
     * its own specific location.
     */

    const SC_MULTIPLE_CHOICES = 300;

    /**
     * Status code (301) indicating that the resource has permanently
     * moved to a new location, and that future references should use a
     * new URI with their requests.
     */

    const SC_MOVED_PERMANENTLY = 301;

    /**
     * Status code (302) indicating that the resource has temporarily
     * moved to another location, but that future references should
     * still use the original URI to access the resource.
     */

    const SC_MOVED_TEMPORARILY = 302;

    /**
     * Status code (303) indicating that the response to the request
     * can be found under a different URI.
     */

    const SC_SEE_OTHER = 303;

    /**
     * Status code (304) indicating that a conditional GET operation
     * found that the resource was available and not modified.
     */

    const SC_NOT_MODIFIED = 304;

    /**
     * Status code (305) indicating that the requested resource
     * <em>MUST</em> be accessed through the proxy given by the
     * <code><em>Location</em></code> field.
     */

    const SC_USE_PROXY = 305;

     /**
     * Status code (307) indicating that the requested resource
     * resides temporarily under a different URI. The temporary URI
     * <em>SHOULD</em> be given by the <code><em>Location</em></code>
     * field in the response.
     */

     const SC_TEMPORARY_REDIRECT = 307;

    /**
     * Status code (400) indicating the request sent by the client was
     * syntactically incorrect.
     */

    const SC_BAD_REQUEST = 400;

    /**
     * Status code (401) indicating that the request requires HTTP
     * authentication.
     */

    const SC_UNAUTHORIZED = 401;

    /**
     * Status code (402) reserved for future use.
     */

    const SC_PAYMENT_REQUIRED = 402;

    /**
     * Status code (403) indicating the server understood the request
     * but refused to fulfill it.
     */

    const SC_FORBIDDEN = 403;

    /**
     * Status code (404) indicating that the requested resource is not
     * available.
     */

    const SC_NOT_FOUND = 404;

    /**
     * Status code (405) indicating that the method specified in the
     * <code><em>Request-Line</em></code> is not allowed for the resource
     * identified by the <code><em>Request-URI</em></code>.
     */

    const SC_METHOD_NOT_ALLOWED = 405;

    /**
     * Status code (406) indicating that the resource identified by the
     * request is only capable of generating response entities which have
     * content characteristics not acceptable according to the accept
     * headerssent in the request.
     */

    const SC_NOT_ACCEPTABLE = 406;

    /**
     * Status code (407) indicating that the client <em>MUST</em> first
     * authenticate itself with the proxy.
     */

    const SC_PROXY_AUTHENTICATION_REQUIRED = 407;

    /**
     * Status code (408) indicating that the client did not produce a
     * requestwithin the time that the server was prepared to wait.
     */

    const SC_REQUEST_TIMEOUT = 408;

    /**
     * Status code (409) indicating that the request could not be
     * completed due to a conflict with the current state of the
     * resource.
     */

    const SC_CONFLICT = 409;

    /**
     * Status code (410) indicating that the resource is no longer
     * available at the server and no forwarding address is known.
     * This condition <em>SHOULD</em> be considered permanent.
     */

    const SC_GONE = 410;

    /**
     * Status code (411) indicating that the request cannot be handled
     * without a defined <code><em>Content-Length</em></code>.
     */

    const SC_LENGTH_REQUIRED = 411;

    /**
     * Status code (412) indicating that the precondition given in one
     * or more of the request-header fields evaluated to false when it
     * was tested on the server.
     */

    const SC_PRECONDITION_FAILED = 412;

    /**
     * Status code (413) indicating that the server is refusing to process
     * the request because the request entity is larger than the server is
     * willing or able to process.
     */

    const SC_REQUEST_ENTITY_TOO_LARGE = 413;

    /**
     * Status code (414) indicating that the server is refusing to service
     * the request because the <code><em>Request-URI</em></code> is longer
     * than the server is willing to interpret.
     */

    const SC_REQUEST_URI_TOO_LONG = 414;

    /**
     * Status code (415) indicating that the server is refusing to service
     * the request because the entity of the request is in a format not
     * supported by the requested resource for the requested method.
     */

    const SC_UNSUPPORTED_MEDIA_TYPE = 415;

    /**
     * Status code (416) indicating that the server cannot serve the
     * requested byte range.
     */

    const SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416;

    /**
     * Status code (417) indicating that the server could not meet the
     * expectation given in the Expect request header.
     */

    const SC_EXPECTATION_FAILED = 417;

    /**
     * Status code (500) indicating an error inside the HTTP server
     * which prevented it from fulfilling the request.
     */

    const SC_INTERNAL_SERVER_ERROR = 500;

    /**
     * Status code (501) indicating the HTTP server does not support
     * the functionality needed to fulfill the request.
     */

    const SC_NOT_IMPLEMENTED = 501;

    /**
     * Status code (502) indicating that the HTTP server received an
     * invalid response from a server it consulted when acting as a
     * proxy or gateway.
     */

    const SC_BAD_GATEWAY = 502;

    /**
     * Status code (503) indicating that the HTTP server is
     * temporarily overloaded, and unable to handle the request.
     */

    const SC_SERVICE_UNAVAILABLE = 503;

    /**
     * Status code (504) indicating that the server did not receive
     * a timely response from the upstream server while acting as
     * a gateway or proxy.
     */

    const SC_GATEWAY_TIMEOUT = 504;

    /**
     * Status code (505) indicating that the server does not support
     * or refuses to support the HTTP protocol version that was used
     * in the request message.
     */

    const SC_HTTP_VERSION_NOT_SUPPORTED = 505;


    public function __toString() {

        $sb = "[Response";
        $sb .= "\n\tcontentCount=".$this->getContentCount();
        $sb .= "\n\tcontentLength=".$this->getContentLength();
        $sb .= "\n\tcontentType=".$this->getContentType();
        $sb .= "\n\theaders=(";
        $headers = $this->getHeaderNames();
        for($i=0; $i < count($headers); $i++) {
            $sb .= "\n\t\t".$headers[$i]."=".strval($this->getHeader($headers[$i]));
            if($i < count($headers) - 1)
                $sb .= ",";
        }
        $sb .= "\n\t)";
        $sb .= ",\n\tmessage=".$this->getMessage();
        $sb .= ",\n\tstatus=".$this->getStatus();
        $sb .= ",\n\tstatusMessage=".$this->getStatusMessage($this->getStatus());
        $sb .= ",\n\tisCommitted=".($this->isCommitted() ? "Yes" : "No");
        $sb .= ",\n\tisSuspended=".($this->isSuspended() ? "Yes" : "No");
        $sb .= ",\n\tisError=".($this->isError() ? "Yes" : "No");
        $sb .= "\n]";

        return $sb;

    }


}



?>